!
!     MUNIPHOT       Main procedure.
!     Copyright (C) 1997-9  Filip Hroch, Masaryk University, Brno, CZ
! 
!=======================================================================
!
      subroutine muniphot ( scifile, comfile )
!
!
! This package was developed for the CCD data analysis on Masaryk
! University in Brno by the DAOPHOT code (P.B.Stetson, 1991)
!
!
! Follow DAOPHOT procedures was re-implemented:
!
!   ATTACH     - Open picture
!
!   FIND       - Find stars
!
!   SKY        - Determination sky value
!
!   PHOTOMETRY - Aperture photometry
!
!   SORT       - Sort the output files according to optionaly parameter
!
!------------------------------------------------------------------------
      use modulephot
      use Param
      use ImageVV

      implicit none
  
      integer, parameter :: maxsky = 10000

!--------------------------------------------------------------------------
!   Warning: muniphot need only MAXSKY parameter!!!!      
!
! Parameters
!
! NOPT is the number of optional parameters which may be altered by the
!      user.
!
! NCMD is the number of commands which the program recognize.
!
! MAXPIC is the maximum number of pixels in an image 2560000 = 1600**2.
!
!                      WARNING
!
! IF ANY OF THE FOLLOWING THREE PARAMETERS IS CHANGED, IT MUST
! ALSO BE CHANGED IN THE FILE CONTAINING THE ROUTINE GETPSF.
! MAXPAR MUST BE CHANGED IN TWO PLACES IN THAT FILE.
!
! MAXPSF is the maximum size of the PSF arrays.
!
! MAXEXP is the maximum number of PSF lookup tables allowed.
!        MAXEXP must be at least 2, because I use PSF as scratch
!        space in FIND.
!
! MAXPAR is the maximum number of parameters allowed in the analytic
!        part of the model PSF.
!
!                End of WARNING
!
! MAXBOX is the length of the side of the largest box that will
!        be used for convolving the image in FIND.  MAXBOX must
!        be less than MAXPSF, because I use the array PSF as
!        scratch space in FIND.
!
! MAXSKY is the maximum number of pixels that will be used in any
!        sky determination.  This will affect the speed of the
!        sky determinations in the SKY and FIND routines (more
!        pixels means slower, of course).  It will also affect
!        the maximum outer sky radius in the PHOTOMETRY routine.
!

      character(len=*) ::  comfile,scifile

      integer, parameter :: LEN=80
      character(len=LEN) :: fcom, sci

      character(len=1) :: answer
      character(len=LEN) ::  com
      character(len=LEN) :: sufix
      real, pointer, save :: d(:,:)
      integer :: nmax
      real :: skymn, skymed, skymod
      integer :: k, i, ncol, nrow, istat,nstar
      real :: data(2), which
      logical :: open
      character(len=LEN) :: file, coofil, magfil, srtfil 
     
     sci = scifile
     fcom = comfile
     open = .false.
      
     write(*,*) ('-',i=1,77)
     write(*,*) 'File: ',trim(sci)
     write(*,*)

     ! optional parameters
     call getopt('mphot.opt',NOPT,opt,omin,omax,istat)
     if( istat /= 0 )then
        write(*,*) 'Error during read optional parameters. Using follow values:'
        do i = 1, NOPT
           write(*,"(A,F10.2)") lbl(i),opt(i)
        enddo
     endif

     ! this cycle read and execute commands
     do 
        call nextcom(fcom,istat)
	if( istat > 0 ) write(*,*) "Can't read the command file."
	if( istat == -1 ) exit   ! end of file
        call getcom(1,com)

	write(*,*) '=>',trim(com)

        ! read the image
	if( com(1:2) == 'AT' .or. com(1:2) == 'at' )then
           call attach(sci, ncol, nrow, d, istat)
           if( istat == 0) then
              open = .true.
           else 
              write(*,*) "Can't open this image."
              open = .false.
           endif

        ! determine sky level
	elseif( com(1:2) == 'SK' .or. com(1:2) == 'sk' )then
           if( open )then
              nmax = min(maxsky, (ncol*nrow)/3)
              call sky(ncol, nrow, d, nmax, opt(4), skymn, skymed, skymod, k)
              write (*,"(A,2F9.1/A,I7)")  &
                   '              Clipped mean and median =', skymn, skymed, & 
                   '   Number of pixels used (after clip) =', k
           else
              call stupid ('   No picture file has been ATTACHed.')
           endif
	
        ! find stars
	elseif( com(1:2) == 'FI' .or. com(1:2) == 'fi' )then
           if( open )then
              coofil = sci
              call switch( coofil, '.COO')
              do i = 1, 2
                 call getcom(i+1,com)
                 read(com,*,iostat=istat) data(i)
                 if( istat /= 0 )then
                    data(i) = 1
                    write(*,*) 'Assumed: Number of frames averaged, summed: ',data
                 endif
              enddo
              call find(ncol, nrow, d, maxsky, opt, nopt, data, coofil, nstar)
           else
              call stupid ('   No picture file has been ATTACHed.')
           endif

           ! aperture photometry
       elseif( com(1:2) == 'PH' .or. com(1:2) == 'ph' )then
         if( open )then
           magfil = sci
           call switch( magfil, '.AP')
           call photsb (ncol, nrow, d, opt(11), coofil, magfil)
         else
            call stupid ('   No picture file has been ATTACHed.')
         endif

      elseif( com(1:2) == 'SO' .or. com(1:2) == 'so' )then
         ! sort of file according to key(s)
         do i = 2, 4
            call getcom(i,com)
            if( i == 2 ) then
               sufix = '.'//com
            endif
            if( i == 3 ) then
               answer = com
               if( answer == 'y' ) answer = 'Y'
            endif
            if( i == 4 ) then
               read(com,*,iostat=istat) which
               if( istat /= 0 ) then
                  write(*,*) "Sort format unrecognized."
                  which = 4.0
               endif
            endif
         enddo

         file = sci
         call switch(file,sufix)
         srtfil = sci
         call switch(srtfil,'.SRT')

         if( .not. open) nstar = 100000

         call sorter (nstar, opt(11), answer, which, file, srtfil)
      else
         write(*,*) '   Unrecognized command: ',trim(com)
      endif

   enddo ! commands

   close(7)

  end




